package com.weiyuanstudio.nextstep.controller;

import com.weiyuanstudio.nextstep.algorithm.snowflake.SnowflakeGenerator;
import com.weiyuanstudio.nextstep.persistence.entity.Book;
import com.weiyuanstudio.nextstep.persistence.repository.BookRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api")
public class BookController {
    private final BookRepository bookRepository;
    private final SnowflakeGenerator snowflakeGenerator;

    public BookController(BookRepository bookRepository, SnowflakeGenerator snowflakeGenerator) {
        this.bookRepository = bookRepository;
        this.snowflakeGenerator = snowflakeGenerator;
    }

    @GetMapping("book")
    public Book firstBook() {
        List<Book> all = bookRepository.findAll();
        if (!all.isEmpty()) {
            return all.get(0);
        }

        return null;
    }

    @GetMapping("book-save")
    public Book saveBook(String name) {
        Book b = new Book();
        b.setIsbn(name);
        b.setTitle(name);
        return bookRepository.save(b);
    }

    @GetMapping("id")
    public String getId() {
        return String.valueOf(snowflakeGenerator.generateId());
    }
}
